<template>
  <view class="">
    <button v-if="savedFilePath" @click="openPDF">查看 PDF1</button>
    <view v-if="loading" style="padding: 12px 0; text-align: center">
      加载中...
    </view>
    <view style="padding: 12px 0; text-align: center">
      {{ error }}
    </view>
    <view style="padding: 12px 0; text-align: center">{{ errMsg }}</view>

    <canvas id="the-canvas"></canvas>
  </view>
</template>

<script>
  import pdfjsLib from "pdfjs-dist";   

  // 关键配置 - 禁用Worker
  pdfjsLib.GlobalWorkerOptions.workerSrc = null;
  pdfjsLib.disableWorker = true;

  // 或者使用更明确的禁用方式
  // pdfjsLib.GlobalWorkerOptions.workerPort = null;

  export default {
    data() {
      return {
        tempFilePath: "",
        loading: false,
        error: "",
        errMsg: "",
        ossHost: "https://qcmp-pro.oss-cn-beijing.aliyuncs.com",
        ossPath: "",

        savedFilePath: "",
      };
    },
    onLoad(options) {
      this.initPDFJS();
      if (options.name && options.name.toLowerCase().endsWith(".pdf")) {
        this.ossPath = options.name;
        this.fetchAndViewPdf(options.name);
      }
    },
    onShow() {},
    methods: {
      initPDFJS() {
        // 关键配置 - 禁用 Worker
        pdfjsLib.GlobalWorkerOptions.workerSrc = null;
        pdfjsLib.disableWorker = true;
      },
      openPDF() {
        debugger;

        // If absolute URL from the remote server is provided, configure the CORS
        // header on that server.
        var url = this.savedFilePath;

        // Loaded via <script> tag, create shortcut to access PDF.js exports.
        // var { pdfjsLib } = globalThis;

        // The workerSrc property shall be specified.
        // pdfjsLib.GlobalWorkerOptions.workerSrc = "/static/pdf.worker.mjs";

        // Asynchronous download of PDF
        var loadingTask = pdfjsLib.getDocument({
          url: url,
          // cMapUrl: "/static/pdfjs/cmaps/",
          cMapPacked: true,
          disableFontFace: true, // 禁用字体加载
          useSystemFonts: true, // 使用系统字体
          disableRange: true, // 禁用范围加载
          disableStream: true, // 禁用流式加载

          disableWorker: true,
          // disableFontFace: true,
          // useSystemFonts: true,
        });
        loadingTask.promise.then(
          function (pdf) {
            console.log("PDF loaded");

            // Fetch the first page
            var pageNumber = 1;
            pdf.getPage(pageNumber).then(function (page) {
              console.log("Page loaded");

              var scale = 1.5;
              var viewport = page.getViewport({ scale: scale });

              // Prepare canvas using PDF page dimensions
              var canvas = document.getElementById("the-canvas");
              var context = canvas.getContext("2d");
              canvas.height = viewport.height;
              canvas.width = viewport.width;

              // Render PDF page into canvas context
              var renderContext = {
                canvasContext: context,
                viewport: viewport,
              };
              var renderTask = page.render(renderContext);
              renderTask.promise.then(function () {
                console.log("Page rendered");
              });
            });
          },
          function (reason) {
            // PDF loading error
            console.error(reason);
          }
        );
      },
      openPDF1() {
        const that = this;
        uni.openDocument({
          filePath: that.savedFilePath,
          fileType: "pdf",
          success: () => {
            console.log("PDF 打开成功");
            that.error = "PDF 打开成功";
          },
          fail: (err) => {
            console.error("打开 PDF 失败:", err);
            that.error = "打开 PDF 失败，请重试";
          },
        });
      },
      fetchAndViewPdf(ossPath) {
        const that = this;
        this.loading = true;
        this.error = "";
        // debugger;
        try {
          uni.downloadFile({
            url: this.ossHost + ossPath,
            success: (res) => {
              // debugger;
              if (res.statusCode === 200) {
                uni.saveFile({
                  tempFilePath: res.tempFilePath,
                  success: (savedRes) => {
                    // debugger;
                    console.log("文件已保存:", savedRes.savedFilePath);
                    that.loading = false;
                    that.error = "加载完成";
                    that.savedFilePath = savedRes.savedFilePath;
                    that.openPDF();
                  },
                  fail: (err) => {
                    // debugger;
                    // console.error("保存文件失败:", err);
                    that.loading = false;
                    that.error = "保存文件失败";
                  },
                });
              }
              that.tempFilePath = res.tempFilePath;
            },
            fail: (err) => {
              // debugger;
              // console.error("下载 PDF 失败:", err);
              that.loading = false;
              that.error = "下载 PDF 失败";
              that.errMsg = err.errMsg;
            },
          });
        } catch (err) {
          that.loading = false;
          this.error = "加载 PDF 失败，请检查网络";
        } finally {
          // this.loading = false;
        }
      },
    },
  };
</script>

<style></style>
